﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;


namespace CCPSIP.vCard
{
    /// <summary>CCPSIP_045：vCard 名片交換 VCF 檔下載 API</summary>
    /// idHeader = 裝置 UUID 前八碼。
    /// checkcode = 裝置限時驗證碼。
    /// vCardExchID = vCard交換請求ID。

    public class vcf_download : IHttpHandler
    {
        public const string kVGEPrefix = "VGE";
        public const char kVGESeparator = ';';

        private string kVCardRootDir = ChrisKit.RootDir + "CCPSIP\\vCard";//ios.ccp


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;


            try
            {
                //【01】取得POST參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string vCardExchID = req.Form["vCardExchID"];//vCard交換ID

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置
                }


                //【02】區分「群組交換」與「個人交換」
                //
                string vCardOwner = null;
                DateTime? vCardTime = null;

                if (vCardExchID.StartsWith(kVGEPrefix))
                {
                    //【03】群組交換
                    //
                    int VGEID = -1;
                    try
                    {
                        string[] keys = vCardExchID.Split(kVGESeparator);
                        VGEID = Convert.ToInt32(keys[1]);
                        vCardOwner = keys[2];
                    }
                    catch
                    {
                        throw new Exception("Error_02: Parameter Error");//參數錯誤
                    }

                    vCardTime = OracleKitVCardGE.getVCardTime(VGEID, userInfo.SIP_Num, vCardOwner);
                    if (vCardTime == null)
                    {
                        throw new Exception("Error_03: vCard record not found");//vCard記錄不存在
                    }
                }
                else
                {
                    //【04】個人交換
                    //
                    int ExchID = -1;
                    try
                    {
                        ExchID = Convert.ToInt32(vCardExchID);
                    }
                    catch
                    {
                        throw new Exception("Error_02: Parameter Error");//參數錯誤
                    }

                    vCardExchInfo vInfo = OracleKitVCard.getExchInfo(ExchID);
                    if (vInfo == null)
                    {
                        throw new Exception("Error_03: vCard record not found");//vCard記錄不存在
                    }

                    if (userInfo.SIP_Num == vInfo.Scanner)
                    {
                        vCardOwner = vInfo.Replier;
                        vCardTime = vInfo.ReplyTime;
                    }
                    else if (userInfo.SIP_Num == vInfo.Replier)
                    {
                        vCardOwner = vInfo.Scanner;
                        vCardTime = vInfo.InitTime;
                    }
                    else
                    {
                        throw new Exception("Error_04: You cannot access this vCard");//無權限存取
                    }
                }


                //【05】組合檔案路徑
                //
                string vcfFile = string.Format(@"{0}_{1:yyyyMMdd_HHmmss}.vcf", vCardOwner, vCardTime);
                string vcfPath = string.Format(@"{0}\{1}\{2}", kVCardRootDir, vCardOwner, vcfFile);
                if (!File.Exists(vcfPath))
                {
                    throw new Exception("Error_05: vCard file not found");//找不到vCard檔案
                }


                //【99】回傳HTTP Header與vCard檔案
                // http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
                //
                FileInfo fInfo = new FileInfo(vcfPath);
                resp.ContentType = "text/vcard";
                resp.AppendHeader("Content-Length", fInfo.Length.ToString());
                resp.AppendHeader("Last-Modified", fInfo.LastWriteTime.ToUniversalTime().ToString("r"));
                resp.AppendHeader("Content-Disposition", ChrisKit.getContentDisposition(vcfFile));
                resp.AppendHeader("Cache-Control", "no-cache");
                resp.WriteFile(vcfPath, true);//Small File
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                string resultStr = ChrisKit.Ex2Xml(ex, false);
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
            }
            finally
            {
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
